package com.wangyadong.hobby.common.utils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;


public class EbUploadUtil {


    public static String uploadPic(HttpServletRequest request, @RequestParam MultipartFile myfile, String imgDiskPath) {
        String result = "";
        try {
            MultipartFile cFile = myfile;
            String tFileName = "";
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            tFileName = format.format(new Date());
            Random random = new Random();
            for (int i = 0; i < 3; i++) {
                tFileName = tFileName + random.nextInt(9);
            }
            //图片
            Object x = request.getParameter("x");//x标
            Object y = request.getParameter("y");//y标
            Object w = request.getParameter("w");//w宽
            Object h = request.getParameter("h");//h高
            File filePath = new File(imgDiskPath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            String originalFilename = cFile.getOriginalFilename();
            int indexOf = originalFilename.indexOf(".");
            int length = originalFilename.length();
            String suff = originalFilename.substring(indexOf, length);
            if (x != null && y != null && w != null && h != null) {
                result = saveFile(filePath.getAbsolutePath(), cFile.getInputStream(), suff
                        , Integer.parseInt((String) x), Integer.parseInt((String) x)
                        , Integer.parseInt((String) w), Integer.parseInt((String) h));
            } else {
                result = saveFile(filePath.getAbsolutePath(), cFile.getInputStream(), suff
                        , 0, 0, 0, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * @param filePath
     * @param inputStream
     * @param suffix
     * @param x
     * @param y
     * @param w
     * @param h
     * @return void    返回类型
     * @throws
     * @Title: saveFile
     * @Description: 保存图片到本地
     */
    private static String saveFile(String filePath, InputStream inputStream, String suffix, int x, int y, int w, int h) {
        String storeName = "";

        if (w == 0 || h == 0) {
            FileOutputStream outputStream = null;
            try {
                storeName = UUID.randomUUID().toString() + suffix;
                outputStream = new FileOutputStream(filePath + File.separator + storeName);
                byte[] buf = new byte[1024];
                int length = 0;
                while ((length = inputStream.read(buf)) != -1) {
                    outputStream.write(buf, 0, length);
                }
                inputStream.close();
                outputStream.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            return storeName;
        }
        String newName = "";
        Random random = new Random();
        //图片裁剪  根据坐标
        for (int i = 0; i < 3; i++) {
            newName = newName + random.nextInt(10);
        }
        newName = newName + storeName;
        //图片裁剪  根据坐标 增加图片格式多样化
        try {
            ImageHelper.cutImage(filePath + newName, filePath + "img_" + newName, x, y, w, h, suffix);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //剪辑后的图片上传文件服务器
        return filePath + "img_" + newName;
    }


    public static String uploadPicBatch(HttpServletRequest request, String fileName, @RequestParam MultipartFile[] myfiles, PrintWriter out) {
        StringBuffer sb = new StringBuffer();
        String result = "";
        try {
            String filePath = request.getSession().getServletContext().getRealPath("/");
            for (MultipartFile cFile : myfiles) {
                if (!cFile.isEmpty()) {
                    //如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中
                    //这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的
                    String tFileName = "";
                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                    tFileName = format.format(new Date());
                    Random random = new Random();
                    for (int i = 0; i < 3; i++) {
                        tFileName = tFileName + random.nextInt(9);
                    }
                    String suff = cFile.getOriginalFilename().substring(cFile.getOriginalFilename().indexOf("."), cFile.getOriginalFilename().length());
                    result = saveFile(filePath, cFile.getInputStream(), suff
                            , 0, 0, 0, 0);
                }
                sb.append("\"");
                sb.append(result);
                sb.append("\"");
                sb.append(",");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return sb.substring(sb.length());
    }

    /**
     * 下载文件
     *
     * @param file
     * @param response
     * @throws IOException
     */
    public static void download(File file, HttpServletResponse response) throws IOException {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(response.getOutputStream());

            long fileLength = file.length();
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(file.getName().getBytes("UTF8"), "ISO8859-1"));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            int bytesRead;
            byte[] bytes = new byte[2048];
            while (-1 != (bytesRead = bis.read(bytes, 0, bytes.length))) {
                bos.write(bytes, 0, bytesRead);
            }
            bos.flush();
        } catch (Exception e) {
            throw new IOException("读取下载失败", e);
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }

    }


    public static Object compressionExcel(HttpServletRequest request, MultipartFile myfil) {
//        String fileType = path.substring(path.lastIndexOf(".") + 1);
//        // return a list contains many list
//        List<List<String>> lists = new ArrayList<List<String>>();
//        //读取excel文件
//        InputStream is = null;
//        try {
//            is = new FileInputStream(path);
//            //获取工作薄
//            Workbook wb = null;
//            if (fileType.equals("xls")) {
//                wb = new HSSFWorkbook(is);
//            } else if (fileType.equals("xlsx")) {
//                wb = new XSSFWorkbook(is);
//            } else {
//                return null;
//            }
//
//            //读取第一个工作页sheet
//            Sheet sheet = wb.getSheetAt(0);
//            //第一行为标题
//            for (Row row : sheet) {
//                ArrayList<String> list = new ArrayList<String>();
//                for (Cell cell : row) {
//                    //根据不同类型转化成字符串
//                    cell.setCellType(Cell.CELL_TYPE_STRING);
//                    list.add(cell.getStringCellValue());
//                }
//                lists.add(list);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (is != null) is.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return lists;
        return null;
    }

    public static void main(String[] args) throws IOException {
        //生成目录
        File file = new File("E:\\data\\.gz\\2019\\9\\18\\316603400994816\\440946392424448\\ddd.txt");
        boolean exists = file.exists();
        if (exists) {
            file.mkdirs();
            file.delete();
        }


    }
}
